import base64
import json
import pickle
import time
from django import http
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseBadRequest, JsonResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from apps.shoppingcart.models import OrderGoods
from utils import constants
from utils.alipay.alipay import zhifubao

from utils.response_code import RETCODE


class CartView(View):
    def get(self, request):
        user = request.user.username
        g_id = request.GET.get('g_id')
        u_name = request.GET.get('u_name')
        num = request.GET.get('num')
        # 用户已登录，操作redis购物车
        redis_conn = get_redis_connection('carts')
        # 查询是否已经有了
        redis_cart = redis_conn.hgetall('carts_%s' % user)

        if redis_cart == {}:
            pl = redis_conn.pipeline()
            # 新增购物车数据
            pl.hincrby('carts_%s' % u_name, g_id, num)
            # 新增选中的状态
            # 执行管道
            pl.execute()
            # 响应结果
            messages.success(request, '添加购物车成功')
            return HttpResponseRedirect('/commodity/?id=%s' % g_id)
        elif redis_cart != {}:
            # # 如果里面有数据就查询
            a = []
            b = []
            for sku_id, count in redis_cart.items():
                x = {
                    int(sku_id): int(count)
                }
                b.append(int(sku_id))
                a.append(x)
            for i in a:
                for s_id in i:
                    # print(s_id)
                    # print(s_id, g_id,11111111111)
                    # print(s_id, i[s_id], g_id)
                    if int(g_id) not in b:
                        pl = redis_conn.pipeline()
                        # 新增购物车数据
                        pl.hincrby('carts_%s' % u_name, g_id, num)
                        # 新增选中的状态
                        # 执行管道
                        pl.execute()
                        # 响应结果
                        messages.success(request, '添加购物车成功')
                        return HttpResponseRedirect('/commodity/?id=%s' % g_id)
                    else:
                        messages.success(request, '库存紧张，限购一个')
                        return HttpResponseRedirect('/commodity/?id=%s' % g_id)








            # print(int(sku_id), int(count), g_id)
            # # 先判断int(sku_id)是否有
            # if int(sku_id) == int(g_id):
            #     print("12")
            #
            #     if int(count) >= 1:
            #         messages.success(request, '库存紧张，限购一个')
            #         return HttpResponseRedirect('/commodity/?id=%s' % g_id)
            #     continue
            # elif int(sku_id) != int(g_id):
            #
            #     if int(count) >= 1 and int(sku_id) == int(g_id):
            #         print(sku_id,count)
            #         continue

            #     print("aaa")
            #     pl = redis_conn.pipeline()
            #     # 新增购物车数据
            #     pl.hincrby('carts_%s' % u_name, g_id, num)
            #     # 新增选中的状态
            #     # 执行管道
            #     pl.execute()
            #     # 响应结果
            #     messages.success(request, '添加购物车成功12')
            #     return HttpResponseRedirect('/commodity/?id=%s' % g_id)

            # 判断是否在redis里面
            # elif int(sku_id) != int(g_id):
            #     print(sku_id, int(g_id))
            #     if not count:
            #         print(11111111111)
            # pl = redis_conn.pipeline()
            # # 新增购物车数据
            # pl.hincrby('carts_%s' % u_name, g_id, num)
            # # 新增选中的状态
            # # 执行管道
            # pl.execute()
            # # 响应结果
            # messages.success(request, '添加购物车成功')
            # return HttpResponseRedirect('/commodity/?id=%s' % g_id)

        # else:
        #         # print(int(sku_id), int(count))
        #         if int(sku_id) == int(g_id) and int(count) >= 1:
        #             messages.success(request, '库存紧张，限购一个')
        #             return HttpResponseRedirect('/commodity/?id=%s' % g_id)
        #         elif int(sku_id) != int(g_id) and int(count) == 0:
        #             pl = redis_conn.pipeline()
        #             # 新增购物车数据
        #             pl.hincrby('carts_%s' % u_name, g_id, num)
        #             # 新增选中的状态
        #             # 执行管道
        #             pl.execute()
        #             # 响应结果
        #             messages.success(request, '添加购物车成功')
        #             return HttpResponseRedirect('/commodity/?id=%s' % g_id)

        #             pl = redis_conn.pipeline()
        #             # 新增购物车数据
        #             pl.hincrby('carts_%s' % u_name, g_id, num)
        #             # 新增选中的状态
        #             # 执行管道
        #             pl.execute()
        #             # 响应结果
        #             messages.success(request, '添加购物车成功')
        #             return HttpResponseRedirect('/commodity/?id=%s' % g_id)
        #         elif int(sku_id) == g_id:
        #             if int(count) >= 1:
        #                 messages.success(request, '库存紧张，限购一个')
        #                 return HttpResponseRedirect('/commodity/?id=%s' % g_id)


class GoodCarView(LoginRequiredMixin, View):
    def get(self, request):
        """展示购物车"""
        user = request.user.username
        # print(user, '=============')
        # 用户已登录，查询redis购物车
        redis_conn = get_redis_connection('carts')
        # 获取redis中的购物车数据
        redis_cart = redis_conn.hgetall('carts_%s' % user)

        # 将redis中的数据构造成跟cookie中的格式一致，方便统一查询
        cart_dict = {}
        for sku_id, count in redis_cart.items():
            cart_dict[int(sku_id)] = {
                'count': int(count),
            }
        # 构造购物车渲染数据
        sku_ids = cart_dict.keys()
        num = 0
        skus = SKU.objects.filter(id__in=sku_ids)
        # print(skus.name)
        cart_skus = []
        for sku in skus:
            # print(sku.price)
            num = num + int(sku.cost_price)
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image,
                'price': str(sku.cost_price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * cart_dict.get(sku.id).get('count')),
                'username': request.user.username
            })
        # print(num)
        context = {
            'cart_skus': cart_skus,
            'price': num
        }

        # 渲染购物车页面
        return render(request, 'cart.html', context)


class DelCarView(LoginRequiredMixin, View):
    def get(self, request):
        user_name = request.GET.get('name')
        sku_id = request.GET.get('sku_id')

        redis_conn = get_redis_connection('carts')
        pl = redis_conn.pipeline()
        # 删除键，就等价于删除了整条记录
        pl.hdel('carts_%s' % user_name, sku_id)
        pl.execute()
        messages.success(request, '删除商品成功')
        return HttpResponseRedirect('/good_car')


class AccountView(LoginRequiredMixin, View):
    def get(self, request):
        user_name = request.user.username
        # 查询购物车
        redis_conn = get_redis_connection('carts')
        # 获取redis中的购物车数据
        redis_cart = redis_conn.hgetall('carts_%s' % user_name)

        cart_dict = {}
        for sku_id, count in redis_cart.items():
            cart_dict[int(sku_id)] = {
                'count': int(count),
            }
        # 构造购物车渲染数据
        sku_ids = cart_dict.keys()
        num = 0
        skus = SKU.objects.filter(id__in=sku_ids)

        for sku in skus:
            num = num + int(sku.cost_price)
        dingdan = hash(time.time)
        url = zhifubao(num, dingdan, user_name)
        return HttpResponseRedirect(url)


class OrderView(LoginRequiredMixin, View):
    def get(self, request):
        dingdan = request.GET.get('dingdan')
        user_name = request.GET.get('id')
        price = request.GET.get('price')
        list1 = []

        redis_conn = get_redis_connection('carts')
        # 获取redis中的购物车数据
        redis_cart = redis_conn.hgetall('carts_%s' % user_name)
        if redis_cart:
            for sku_id, count in redis_cart.items():
                list1.append(int(sku_id))

            pl = redis_conn.pipeline()
            # 删除键，就等价于删除了整条记录
            for i in list1:
                pl.hdel('carts_%s' % user_name, i)
            pl.execute()

        OrderGoods.objects.create(user_name=user_name, order_num=dingdan, price=price)

        messages.success(request, "支付成功 跳转到首页")
        return redirect(reverse('index:index'))
